package com.yuven.appframework.util;


import static android.content.ContentValues.TAG;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.util.List;

public class LocationUtils {

    private Context mContext;
    private volatile static LocationUtils uniqueInstance;

    private LocationUtils(Context context) {
        mContext = context;
    }

    //采用Double CheckLock(DCL)实现单例
    public static LocationUtils getInstance(Context context) {
        if (uniqueInstance == null) {
            synchronized (LocationUtils.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new LocationUtils(context);
                }
            }
        }
        return uniqueInstance;
    }


    /**
     * 获取设备的位置信息
     */
    public Location getDeviceLocation() {
        Location location = null;
        try {
            LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            if (locationManager == null||ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return null;
            }

            String locationProvider;
            List<String> providers = locationManager.getProviders(true);
            if (providers != null && providers.contains(LocationManager.NETWORK_PROVIDER)) {
                //如果是网络定位
                Log.d(TAG, "如果是网络定位");
                locationProvider = LocationManager.NETWORK_PROVIDER;
            } else if (providers != null && providers.contains(LocationManager.GPS_PROVIDER)) {
                //如果是GPS定位
                Log.d(TAG, "如果是GPS定位");
                locationProvider = LocationManager.GPS_PROVIDER;
            } else {
                Log.d(TAG, "没有可用的位置提供器");
                return null;
            }
            location = locationManager.getLastKnownLocation(locationProvider);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return location;
    }




}
